package com.okay.progress

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.Log
import android.view.View
import androidx.core.content.ContextCompat
import com.okay.testclass.R
import com.okay.util.DensityUtils

/**
 * 显示抬头率的横向进度条
 */
class ProgressBarView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    private var paint: Paint? = null
    private var minProgress: Float = 25f//默认最小值就是25%
    private var progress: Float = minProgress

    private var sizeMax: Float = 0f  //外圈圆角
    private var sizeMin: Float = 0f  //内圈圆角弧度

    private var spaceSize: Float = DensityUtils.dp2px(context, 0.5f).toFloat()//内外圈的间距

    /**
     * 添加进度
     */
    fun setSize(progress: Float) {
        Log.d("test111", "progress:  $progress")
        if (progress > 100 || progress < 0) return

        if (progress >= minProgress) {//必须得大于最小值才可以赋值
            this.progress = progress
        } else {
            this.progress = minProgress
        }
        postInvalidate()
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)

        //初始化画笔
        paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint?.color = Color.WHITE
        paint?.style = Paint.Style.FILL
        paint?.strokeWidth = 1f

        //外圈进度条长宽
        val width = width.toFloat()
        val height = height.toFloat()
        //内圈进度条长宽
        val minWidth = width - (spaceSize * 2)
        val minHeight = height - (spaceSize * 2)

        sizeMax = height / 2
        sizeMin = minHeight / 2

        Log.d("test111", "width:  $width,height:  $height")
        //绘制外圈圆角矩形
        canvas?.drawRoundRect(RectF(0f, 0f, width, height), sizeMax, sizeMax, paint!!)

        if (progress > 80) {
            paint?.color = ContextCompat.getColor(context, R.color.FF00B34D)
        } else if (progress < 50) {
            paint?.color = ContextCompat.getColor(context, R.color.FFFE0300)
        } else {
            paint?.color = ContextCompat.getColor(context, R.color.FFF0A006)
        }

        var ww: Float = minWidth / 100  //每1%占用的宽度
        Log.d(
            "test111",
            "ww:  $ww \n  (ww * progress) : ${(ww * progress)}  \n  minWidth   : $minWidth"
        )
        //绘制内圈圆角矩形
        var rectf = RectF(spaceSize, spaceSize, (ww * progress), minHeight + spaceSize)
        canvas?.drawRoundRect(rectf, sizeMin, sizeMin, paint!!)
    }

}